package gui.popup;

import gui.App;
import gui.table.AutoTable;

import java.util.Date;

import models.Client;
import models.Payment;

import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Text;

public class PaymentPopup extends Popup<Payment>{
	
	private Text amountText, commentText;
	private DateTime datum;
	private AutoTable<Client> clientTable;
	private Client preselected;

	public PaymentPopup(App app) {
		super(app);
	}
	
	/**
	 * Set a preselected client for the next opened popup.
	 * @param client
	 */
	public void setPreSelected(Client client) {
		preselected = client;
	}

	@Override
	public Payment createEmptyModel() {
		return new Payment();
	}

	@Override
	public void buildForm(Composite formPanel, Payment payment) {
		setTitle_modelType("Betaling");
		
		formPanel.setLayout(new GridLayout(2, false));

		createFormItem_label(formPanel, "Klant");
		Client client = preselected == null? payment.getClient(): preselected;
		preselected = null;
		clientTable = createFormItem_client(formPanel, client);
	    
		createFormItem_label(formPanel, "Bedrag");
		amountText = createFormItem_text(formPanel, ""+payment.getAmount());

		createFormItem_label(formPanel, "Datum");
		datum = createFormItem_date(formPanel, payment.getDate());

		createFormItem_label(formPanel, "Commentaar");
		commentText = createFormItem_longtext(formPanel, payment.getComment());
		
	}

	@Override
	public boolean isDataValid() {
		ParseError errorBox = new ParseError();	

		Client client = clientTable.getSelected();
		if(client == null) {
			errorBox.obligatedField(null);
		}
		
		String amount = amountText.getText();
		errorBox.obligatedField(amount);
		
		String comments = commentText.getText();
		errorBox.obligatedField(comments);
		errorBox.fieldLength(comments, 2000);		
		
		try {
			Double.parseDouble(amount);
		} catch (NumberFormatException e) {
			errorBox.parseError();
		}
		
		if(errorBox.errorsPresent()) {
			alertInvalidData(errorBox.getErrorString());
			return false;
		}
		else {
			return true;
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void updateModel(Payment payment) {
		payment.setClient(clientTable.getSelected());
		payment.setAmount(Double.parseDouble(amountText.getText()));
		payment.setDate(new Date(datum.getYear()-1900, datum.getMonth(), datum.getDay()));
		payment.setComment(commentText.getText());		
	}
}
